package com.demo.draw;

import com.demo.controller.MoveSolution;
import com.demo.model.Card;
import com.demo.view.CardsView;


public class MovingCard implements Runnable {
    private final Card card;
    private final int endX, endY, row, col, direction;

    public MovingCard(Card card, int nextRow, int nextCol, int direction) {
        this.card = card;
        this.direction = direction;
        endX = CardsView.transColumnToX(nextCol);
        endY = CardsView.transRowToY(nextRow);
        row = nextRow;
        col = nextCol;
    }

    @SuppressWarnings("BusyWait")
    @Override
    public void run() {
        CardsView cardsView = CardsView.getInstance();
        int startX = card.getX();
        int startY = card.getY();
        int distance = Math.abs(endX - startX + endY - startY);
        int x = startX, y = startY;
        // 时间
        int t = 12;
        // 耗费t移动的位移（速度）
        int v = 1 + distance / t;
        while (Math.abs(x - startX + y - startY) < distance) {
            cardsView.repaint();
            x += MoveSolution.get_dx(direction) * v;
            y += MoveSolution.get_dy(direction) * v;
            if (Math.abs(x - startX + y - startY) > distance) {
                x = endX;
                y = endY;
            }
            card.setX(x);
            card.setY(y);
            try {
                Thread.sleep(t);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        card.setX(endX);
        card.setY(endY);
        card.setRow(row);
        card.setColumn(col);
        cardsView.repaint();
    }
}
